<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10">
        <div class="mainor_form batch-wrap small-top">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="90px"
            id="form"
          >
            <el-form-item label="商品：" prop="goods_spu_id">
              <change-goods-input
                ref="changeGoodsInput"
                isInventory
                @clear="
                  () => {
                    this.form.goods_spu_id = '';
                  }
                "
                @sendValue="
                  (data) => {
                    this.form.goods_spu_id = data.id;
                  }
                "
              ></change-goods-input>
            </el-form-item>
            <el-form-item label="商品分类：" prop="category_id" class="wid220">
              <el-cascader
                v-model="form.category_id"
                :options="options"
                :props="defaultProps"
                @change="getArticleList"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="库存预警：" prop="warn">
              <el-select
                v-model.trim="form.warn"
                placeholder="库存预警"
                class="wid220"
                @change="getArticleList"
              >
                <el-option label="所有" value=""></el-option>
                <el-option
                  v-for="(item, index) in upper_lower"
                  :key="index"
                  :label="item"
                  :value="parseInt(index)"
                ></el-option>
              </el-select>
            </el-form-item>
            <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
              <el-button @click="exportMethodDia">导出</el-button>
            </MainFormBtn>
            <div class="more el-form-item" @click="more">
              <span>更多</span>
              <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
            </div>
            <div class="clearfix"></div>
            <el-collapse-transition>
              <div v-show="moredata">
                <div class="clearfix"></div>
                <el-form-item label="正负库存：" prop="plus_min">
                  <el-select
                    v-model.trim="form.plus_min"
                    placeholder="库存预警"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value="0"></el-option>
                    <el-option label="正库存" value="1"></el-option>
                    <el-option label="负库存" value="2"></el-option>
                  </el-select>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                    <el-button @click="exportMethodDia">导出</el-button>
                  </MainFormBtn>
                </el-form-item>
              </div>
            </el-collapse-transition>
          </el-form>
        </div>
        <div class="main-controls-wrap mg-t-4">
          <div>
            <router-link :to="{ path: '/warehouse/now/record', query: { time: form.send_time } }"><el-button>操作记录</el-button></router-link >
            <router-link to="/warehouse/now/library"><el-button>库区管理</el-button></router-link>
          </div>
          <div class="batch-wrap-right">
            <el-checkbox class="mainsu_tes" v-model="display_zero_inventory" @change="canceledChange" >库存为0不显示</el-checkbox>
          </div>
        </div>
        <div class="main_table">
          <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list.data"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
          :header-cell-class-name="this.$verticaline"
          :summary-method="getSummaries"
          show-summary
          :height="borderHeight"
          :header-cell-style="tableHeightStyle"
          @header-dragend="changeTableWidth"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column
            label="商品名称"
            prop="spu_name"
            :width="tableWidth[hash + 'spu_name'] || 150"
          >
            <template slot-scope="scope"
              ><span v-if="scope.row.spu_name">
                {{ scope.row.goods.name }}【{{
                  scope.row.spu_name.title
                }}】</span
              ></template
            >
          </el-table-column>
          <el-table-column
            label="SKU编码"
            prop="goods_spu_code"
            :width="tableWidth[hash + 'goods_spu_code']"
          />
          <el-table-column
            label="单位"
            prop="spu_unit.title"
            :width="tableWidth[hash + 'spu_unit.title']"
          />
          <el-table-column
            label="商品分类"
            prop="category_name"
            :width="tableWidth[hash + 'category_name']"
          />
          <el-table-column
            label="在途库存"
            prop="transit_num"
            :width="tableWidth[hash + 'transit_num']"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.transit_num ? scope.row.transit_num : "0.00"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="当前库存"
            prop="inventory.num"
            :width="tableWidth[hash + 'inventory.num']"
          >
            <template slot-scope="{ row }">
              <span :class="{ lower_upper: row.lower_upper==='yes', upper_lower: row.upper_lower==='yes' }">
                {{ row.inventory.num }}
              </span>
            </template>
          </el-table-column>

          <el-table-column
            label="库存均价"
            prop="inventory.price"
            class-name="main_hei"
            :width="tableWidth[hash + 'inventory.price'] || 120"
          >
            <template slot-scope="scope">
              <div class="mainus_pe" v-if="scope.row.inventory ? true : false">
                <div v-if="!scope.row.freight_unit">
                  {{ scope.row.inventory ? scope.row.inventory.price : "" }}
                  <svg
                    aria-hidden="true"
                    class="main_page_svg"
                    width="13"
                    height="13"
                    @click="freighta(scope.$index, 'freight_unit')"
                  >
                    <use xlink:href="#icon-commodity_modify" />
                  </svg>
                </div>
                <div v-else class="boxnr">
                  <el-input
                    v-model="scope.row.inventory.price"
                    placeholder="库存单价"
                    class="wid80"
                  ></el-input>
                  <div class="boxnr svg_box">
                    <svg
                      aria-hidden="true"
                      class="main_page_svg marginLeft5"
                      width="20"
                      height="20"
                      @click="
                        inputBlur(
                          scope.row.inventory.price,
                          scope.$index,
                          'freight_unit',
                          'price'
                        )
                      "
                    >
                      <use xlink:href="#icon-index_tick" />
                    </svg>
                    <svg
                      aria-hidden="true"
                      class="main_page_svg marginLeft5"
                      width="12"
                      height="12"
                      @click="
                        (scope.row.inventory.price =
                          scope.row.inventory.price_data),
                          (scope.row.freight_unit = false)
                      "
                    >
                      <use xlink:href="#icon-index_cross" />
                    </svg>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="近一次出库成本"
            prop="outbound_cost"
            :width="tableWidth[hash + 'outbound_cost'] || 120"
          />

          <el-table-column
            label="库存金额"
            prop="allmoney"
            :width="tableWidth[hash + 'allmoney']"
          />

          <el-table-column
            label="库存上限"
            prop="inventory.upper"
            class-name="main_hei"
            :width="tableWidth[hash + 'inventory.upper'] || 120"
          >
            <template slot-scope="scope">
              <div class="mainus_pe" v-if="scope.row.inventory ? true : false">
                <div v-if="!scope.row.freight_upper">
                  {{ scope.row.inventory ? scope.row.inventory.upper : "" }}
                  <svg
                    aria-hidden="true"
                    class="main_page_svg"
                    width="13"
                    height="13"
                    @click="freighta(scope.$index, 'freight_upper')"
                  >
                    <use xlink:href="#icon-commodity_modify" />
                  </svg>
                </div>
                <div v-else class="boxnr">
                  <el-input
                    v-model="scope.row.inventory.upper"
                    placeholder="库存上限"
                    class="wid80"
                  ></el-input>
                  <div class="boxnr svg_box">
                    <svg
                      aria-hidden="true"
                      class="main_page_svg marginLeft5"
                      width="20"
                      height="20"
                      @click="
                        inputBlur(
                          scope.row.inventory.upper,
                          scope.$index,
                          'freight_upper',
                          'upper'
                        )
                      "
                    >
                      <use xlink:href="#icon-index_tick" />
                    </svg>
                    <svg
                      aria-hidden="true"
                      class="main_page_svg marginLeft5"
                      width="12"
                      height="12"
                      @click="
                        (scope.row.inventory.upper =
                          scope.row.inventory.upper_data),
                          (scope.row.freight_upper = false)
                      "
                    >
                      <use xlink:href="#icon-index_cross" />
                    </svg>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="库存下限"
            prop="inventory.lower"
            class-name="main_hei"
            :width="tableWidth[hash + 'inventory.lower'] || 120"
          >
            <template slot-scope="scope">
              <div class="mainus_pe" v-if="scope.row.inventory ? true : false">
                <div v-if="!scope.row.freight_lower">
                  {{ scope.row.inventory ? scope.row.inventory.lower : "" }}
                  <svg
                    aria-hidden="true"
                    class="main_page_svg"
                    width="13"
                    height="13"
                    @click="freighta(scope.$index, 'freight_lower')"
                  >
                    <use xlink:href="#icon-commodity_modify" />
                  </svg>
                </div>

                <div v-else class="boxnr">
                  <el-input
                    v-model="scope.row.inventory.lower"
                    placeholder="库存下限"
                    class="wid80"
                  ></el-input>
                  <div class="boxnr svg_box">
                    <svg
                      aria-hidden="true"
                      class="main_page_svg marginLeft5"
                      width="20"
                      height="20"
                      @click="
                        inputBlur(
                          scope.row.inventory.lower,
                          scope.$index,
                          'freight_lower',
                          'lower'
                        )
                      "
                    >
                      <use xlink:href="#icon-index_tick" />
                    </svg>
                    <svg
                      aria-hidden="true"
                      class="main_page_svg marginLeft5"
                      width="12"
                      height="12"
                      @click="
                        (scope.row.inventory.lower =
                          scope.row.inventory.lower_data),
                          (scope.row.freight_lower = false)
                      "
                    >
                      <use xlink:href="#icon-index_cross" />
                    </svg>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="存放位置"
            prop="inventory.reservoir_str"
            class-name="main_hei"
            :width="tableWidth[hash + 'inventory.reservoir_str'] || 160"
          >
            <template slot-scope="scope">
              <div class="boxnr">
                <div>
                  {{ scope.row.inventory.reservoir_str }}
                  <svg
                    aria-hidden="true"
                    class="main_page_svg marginLeft5 point"
                    width="13"
                    height="13"
                    @click="selectChange(scope.row)"
                  >
                    <use xlink:href="#icon-commodity_modify" />
                  </svg>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" class-name="main_hei" label-class-name="main-center">
            <template slot-scope="scope">
              <el-link
                type="primary"
                @click="unitConverts(scope.row)"
                v-if="scope.row.goods.transfer != 1"
                >单位转换</el-link
              >
              <el-link type="primary" @click="settingBound(scope.row)"
                >设置库存上下限</el-link
              >
              <el-link type="primary" @click="selectChange(scope.row)"
                >存放位置</el-link
              >
            </template>
          </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div class="main_page_l">
            库存总金额：
            <em>{{ header_all_money }}</em>
          </div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>

      <el-dialog
        title="导出"
        :visible.sync="exportFormVisible"
        class="main_dialog dialog500"
        @close="type = list.field"
      >
        <div class="export">你选择了{{ this.selectArr.length }}条数据</div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="exportFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="exportConfim" v-repeatClick
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        title="编辑库区/货架/货位"
        :visible.sync="selectVisible"
        class="main_dialog dialog500"
        @close="close(1, (selectVisible = false))"
      >
        <div class="main_tree_b">
          <!-- <el-tree
            ref="tree"
            :data="selList"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :default-checked-keys="defaultkeys"
            highlight-current
            :props="selProps"
            style="min-height: 350px"
            @check-change="handleClick"
          >
          </el-tree> -->

          <el-cascader
            popper-class="cascader"
            ref="cascader"
            placeholder="请选择库区/货架/货位"
            class="wid240"
            clearable
            :options="selList"
            :props="selProps"
            v-model="checkedId"
            @change="changeSel"
          >
          </el-cascader>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="close(2, (selectVisible = false))"
            >取 消</el-button
          >
          <el-button type="primary" @click="selSubmit">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title="设置上下限"
        :visible.sync="bound.show"
        class="main_dialog dialog500"
        @close="bound.show = false"
      >
        <div class="goods">
          <div class="goods-top">
            <div class="name">
              商品:<span v-if="bound.data.spu_name">
                {{ bound.data.goods.name }}【{{
                  bound.data.spu_name.title
                }}】</span
              >
            </div>
            <div class="unit">
              单位:<span v-if="bound.data.spu_unit">{{
                bound.data.spu_unit.title
              }}</span>
            </div>
            <div class="stock">
              库存:<span v-if="bound.data.inventory">{{
                bound.data.inventory.num
              }}</span>
            </div>
          </div>
          <div class="goods-center">现有库存上下限设置</div>
          <div class="goods-bottom">
            <div class="box">
              <div>库存上限：</div>
              <el-input
                class="wid140"
                v-if="bound.data.inventory"
                v-model="bound.data.inventory.upper"
                @input="handleNumInput(bound.data.inventory, 'upper')"
                placeholder="库存上限"
              ></el-input>
            </div>
            <div class="box">
              <div>库存下限：</div>
              <el-input
                class="wid140"
                v-if="bound.data.inventory"
                v-model="bound.data.inventory.lower"
                @input="handleNumInput(bound.data.inventory, 'lower')"
                placeholder="库存下限"
              ></el-input>
            </div>
          </div>
          <div style="margin-top: 10px; font-size: 12px; color: #999999">
            填写库存下限值，例如20，售卖库存低于20，系统会自动预警。
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="bound.show = false">取 消</el-button>
          <el-button type="primary" @click="boundSubmit">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="单位转换"
        :visible.sync="unitConvert.show"
        class="main_dialog dialog600"
        @close="unitConvert.show = false"
      >
        <div class="goods">
          <div class="goods-top">
            <div class="name">
              商品:<span> {{ goodsInfo.goods_name }}</span>
            </div>
            <div class="unit">
              单位:<span>{{ goodsInfo.unit }}</span>
            </div>
            <div class="stock">
              库存:<span>{{ goodsInfo.stock_num }}</span>
            </div>
          </div>
          <div class="goods-center" style="margin-bottom: 0">
            <template v-if="!unitDisabled">
              <el-input
                class="wid140"
                v-if="unitConvert.data.spu_list"
                :value="calculateInputValue"
                placeholder="请输入>0的整数"
                disabled
              ></el-input>
            </template>
            <template v-else>
              <el-input
                class="wid140"
                v-model="unitForm.num"
                placeholder="请输入>0的整数"
              ></el-input>
            </template>
            <span style="margin: 0 10px">{{ goodsInfo.unit }}</span>
            <template v-if="unitDisabled">
              <el-input
                class="wid140"
                v-if="unitConvert.data.spu_list"
                disabled
                :value="calculateInputValue"
                placeholder="请输入>0的整数"
              ></el-input>
            </template>
            <template v-else>
              <el-input
                class="wid140"
                v-model="unitForm.num"
                placeholder="请输入>0的整数"
              ></el-input>
            </template>
            <el-select
              v-model="unitForm.spu_id"
              placeholder="请选择"
              class="wid100"
              style="margin: 0 15px 0"
              @change="changeSpu"
            >
              <el-option
                v-for="item in unitConvert.data.spu_list"
                :key="item.id"
                :label="item.unit"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <span v-if="unitConvert.data.spu_list">
              {{
                (unitConvert.data.spu_list[unitConvert.activeSpu] || {}).desc
              }}
            </span>
          </div>
          <div class="goods-bottom" style="color: red">
            <span v-if="parseFloat(unitForm.num) > parseFloat(goodsInfo.stock_num)">
              数值不能大于现有库存
            </span>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="unitConvert.show = false">取 消</el-button>
          <el-button type="primary" @click="unitSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import { mapGetters } from "vuex";
import {
  storage_index,
  storage_update,
  export_storage_now,
  reservoir_index,
  change_Field,
  unit_changeData,
  unit_change,
} from "@/api/warehouse/warehouseNow";
import { setting_company } from "@/api/currency";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime, recursion, category, exportMethod , handleNumInput } from "@/utils/index";

export default {
  mixins: [mixins],
  directives: {
    // 聚焦元素
    focus: {
      inserted(el) {
        el.querySelector("input").focus();
      },
    },
  },
  computed: {
    ...mapGetters(["avatar"]),
    reverseSum() {
      return this.percent_list.reverse();
    },
    // 单位转化弹框的商品信息
    goodsInfo() {
      return this.unitConvert.data.goods_info || {};
    },
    // 计算转化数量
    calculateInputValue(){
      const spu = this.unitConvert.data.spu_list[this.unitConvert.activeSpu];
      return spu ? (spu.package_num * this.unitForm.num).toFixed(2) : 0;
    }
  },

  components: {},
  data() {
    return {
      exportMethod,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      listLoading: false,
      // 搜索
      form: {
        pid: "",
        category_id: [],
        goods_spu_id: "",
        warn: "",
        plus_min: "", //正负库存
      },
      // 库存为o不显示
      display_zero_inventory: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      offsetParent: true,
      // 批量同步
      percent_gs: 0,
      percent: 0,
      percent_list: [],
      addedFormVisible: false,
      // 全选
      selectArr: [],
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      header_all_money: 0,
      list_money: 0,
      // 库存预警
      upper_lower: {},
      // 焦点
      offsetParent: true,
      exportFormVisible: false,
      selectVisible: false,
      defaultkeys: [],
      selProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      selList: [],
      id: "",
      checkedId: "",
      moredata: false,
      // 设置上下限
      bound: {
        show: false,
        data: {},
      },
      // 单位转化
      unitConvert: {
        show: false,
        data: {},
        activeSpu: 0,
      },
      // 禁用状态
      unitDisabled: false,
      // 提交数据
      unitForm: {
        inventory_id: "",
        spu_id: "",
        num: "",
      },
    };
  },
  mounted() {
    window.Echo.channel(
      "batchDispatchPricing." + this.avatar.company_id
    ).listen("BatchDispatchPricingEvent", (e) => {
      this.percent_gs = parseInt(this.percent_gs) + 1;
      if ((this.percent_gs / this.selectArr.length) * 100 >= 100) {
        this.percent = 100;
        return;
      }
      this.percent =
        this.percent_gs / this.selectArr.length
          ? parseInt((this.percent_gs / this.selectArr.length) * 100)
          : 0;
      if (e.notice.msg == "ok") {
        this.percent_list.push({
          num: this.percent,
          type: 1,
          order_id: e.notice.goods_spu_id,
        });
      } else {
        this.percent_list.push({
          num: this.percent,
          type: 2,
          order_id: e.notice.goods_spu_id,
        });
      }
    });
  },
  created() {
    this.getNumerical(200);
    this.storage_index();
  },
  methods: {
    handleNumInput,
    more() {
      this.moredata = !this.moredata;
    },
    getSearchFor() {
      this.getArticleList();
    },
    startGetting() {
      this.getArticleList();
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push(item.id);
      });
    },
    exportMethodDia() {
      if (this.selectArr.length > 0) {
        this.exportFormVisible = true;
      } else {
        this.exportConfim();
        // this.$message.error("你还未选择导出的数据");
      }
    },
    // 导出确认
    exportConfim() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      form.ids = this.selectArr.join("-");
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, form)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_storage_now(data).then((res) => {
        this.exportMethod(res, "当前库存", notify);
      });
      this.exportFormVisible = false;
    },
    // 库存为0b=不显示
    canceledChange(val) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                display_zero_inventory: val ? 1 : 0,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { display_zero_inventory: val ? 1 : 0 }
      );
      setting_company(data).then((res) => {
        if (res.errcode == 0) {
          this.storage_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.storage_index();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.$refs["changeGoodsInput"].name = "";
      this.form.plus_min = "";
      this.storage_index();
    },
    storage_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.current,
        this.list_form()
      );
      storage_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.display_zero_inventory =
            res.data.display_zero_inventory == 1 ? true : false;
          this.options = recursion(res.data.categoryList, true);
          let category = res.data.category;
          this.header_all_money = res.data.money;
          let list_money = 0;
          res.data.list.data.map((e) => {
            if (e.inventory) {
              e.inventory.price_data = e.inventory.price;
              e.inventory.upper_data = e.inventory.upper;
              e.inventory.lower_data = e.inventory.lower;
            }
            e.show = false;
            e.freight_unit = false;
            e.freight_upper = false;
            e.freight_lower = false;
            if (e.inventory && e.inventory.price) {
              e.allmoney = this.$toFixed(
                parseFloat(e.inventory.num) * parseFloat(e.inventory.price)
              );
            }

            if (e.allmoney == undefined || e.allmoney == "") {
            } else {
              list_money += Number(e.allmoney);
            }

            e.category_name = "";
            let title = [];
            if (category[e.goods.pid]) {
              title.push(category[e.goods.pid].title);
              if (
                category[e.goods.pid].selfNext &&
                category[e.goods.pid].selfNext[e.goods.category_id]
              ) {
                title.push(
                  category[e.goods.pid].selfNext[e.goods.category_id].title
                );
              }
            }
            e.category_name = title.join("|");
          });
          this.list_money = this.$toFixed(Number(list_money));
          this.list = res.data;
          this.upper_lower = res.data.upper_lower;
          this.totalCount = res.data.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      return form;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.storage_index();
    },
    changePage(page) {
      this.current.page = page;
      this.storage_index();
    },

    // 点击排序
    freighta(index, name) {
      if (this.offsetParent) {
        this.list.list.data[index][name] = !this.list.list.data[index][name];
      }
    },

    inputBlur(val, index, name, type) {
      this.offsetParent = false;
      if (/^(\d+\.?)?\d{0,2}$/.test(parseFloat(val)) && val != "") {
        this.list.list.data[index][name] = !this.list.list.data[index][name];
        this.offsetParent = true;
        this.storage_update(val, this.list.list.data[index].inventory.id, type);
      }
    },

    storage_update(val, id, type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { id: id, field: type, value: val })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id, field: type, value: val }
      );
      storage_update(data).then((res) => {
        if (res.errcode == 0) {
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 表单合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        switch (index) {
          case 1:
            sums[index] = "合计";
            break;
          case 9:
            sums[index] = this.list_money;
        }
      });

      return sums;
    },

    selectChange(row) {
      this.id = row.inventory.id;
      let ids = row.inventory.reservoir_id;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name
        // { id: row.inventory.reservoir_id }
      );
      reservoir_index(data).then((res) => {
        if (res.errcode == 0) {
          this.selList = res.data;
          this.selectVisible = true;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    changeSel() {
      let list = this.$refs["cascader"].getCheckedNodes();
      if (list.length > 0) {
        this.checkedId = list[0].value;
      }
    },
    selSubmit() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                id: this.id,
                value: this.checkedId,
                field: "reservoir_id",
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id, value: this.checkedId, field: "reservoir_id" }
      );
      change_Field(data).then((res) => {
        if (res.errcode == 0) {
          this.selectVisible = false;
          this.storage_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    handleClick(data, checked, node) {
      if (checked == true) {
        this.checkedId = data.id;
        this.$refs.tree.setCheckedNodes([data]);
      }
    },
    close(type) {
      if (type == 1) {
        this.checkedId = "";
      } else {
        this.checkedId = "";
      }
    },
    // 设置下上限
    settingBound(row) {
      this.bound.show = true;
      this.bound.data = JSON.parse(JSON.stringify(row));
    },
    // 提交设置上下限
    boundSubmit() {
      let id = this.bound.data.inventory.id;
      let upper = this.bound.data.inventory.upper;
      let lower = this.bound.data.inventory.lower;
      if(!upper || !lower) {
        this.$message.error(`${!upper?'库存上限':'库存下限'}未填写`)
        return 
      }
      Promise.all([
        this.newstorage_update(upper, id, "upper"),
        this.newstorage_update(lower, id, "lower"),
      ]).then((res) => {
        try {
          res.forEach((item) => {
            if (item.errcode != 0) {
              throw new Error(item.errmsg);
            }
          });
          this.bound.show = false;
          this.storage_index();
        } catch (e) {
          this.$message.error(e);
        }
      });
    },
    // 上下限提交
    newstorage_update(val, id, type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { id: id, field: type, value: val })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id, field: type, value: val }
      );
      return storage_update(data);
    },
    // 单位转换
    unitConverts(row) {
      // 打开的时候将提交数据清空
      this.unitForm = {
        inventory_id: "",
        spu_id: "",
        num: "",
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, { inventory_id: row.inventory.id })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { inventory_id: row.inventory.id }
      );
      unit_changeData(data).then((res) => {
        if (res.errcode == 0) {
          this.unitConvert = {
            show: true,
            data: res.data,
            activeSpu: 0,
          };
          this.unitForm = {
            inventory_id: row.inventory.id,
            spu_id: res.data.spu_list[0].id,
            num: "",
          };
          this.unitDisabled = res.data.goods_info.base != 1;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 切换规格
    changeSpu(val) {
      let index = this.unitConvert.data.spu_list.findIndex(
        (item) => item.id == val
      );
      this.unitConvert.activeSpu = index;
    },
    // 提交单位转化
    unitSubmit() {
      if (parseFloat(this.unitForm.num) > parseFloat(this.unitConvert.data.goods_info.stock_num)) {
        this.$message.error("库存不足");
        return;
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.unitForm)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.unitForm
      );
      unit_change(data).then((res) => {
        if (res.errcode == 0) {
          this.unitConvert.show = false;
          this.storage_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 180px);
  }

  .main_dialog {
    .progress_list {
      margin-top: 10px;
      p {
        height: 24px;
        line-height: 24px;
      }
      .progress_list_red {
        color: red;
      }
      .progress_list_su {
        color: #03a98e;
      }
    }
  }
}
.export {
  text-align: center;
  font-size: 18px;
  margin-top: 20px;
}

// 对错 svg展示
.svg_box {
  display: flex;
  flex-direction: column;
}
/deep/.main_dialog .el-checkbox {
  margin-bottom: 0px;
}
/deep/.el-tree-node__content {
  height: 30px;
}
.point {
  cursor: pointer;
}

/deep/.el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}

/deep/.el-cascader-panel .el-radio__input {
  visibility: hidden;
}
/* 这个样式针对IE有用，不考虑IE的可以不用管*/
/deep/.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}

.mainsu_tes {
  height: 33px;
  line-height: 33px;
}

/deep/ .el-form-item--small.el-form-item {
  margin-bottom: 10px !important;
}
.goods {
  &-top {
    width: 95%;
    display: flex;
    justify-content: space-between;
  }
  &-center {
    margin: 30px 0 20px;
  }
  &-bottom {
    display: flex;
    height: 35px;
    line-height: 35px;
    justify-content: space-between;
  }
}

.upper_lower {
  color: #E6A23C;
}
.lower_upper {
  color: red;
}
</style>
